<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 商家销量统计
 * Class Order
 */
class Merchant extends MY_Controller
{
    /**
     * @var ConsumerOrderModel
     */
    public $mOrder = null;
    /**
     * @var MerchantUserModel
     */
    public $mMerchant = null;
    /**
     * @var consumerUserModel
     */
    public $mConsumer = null;
    /**
     * @var ConsumerProductModel
     */
    public $mProduct = null;
    /**
     * @var ConsumerCategoryModel
     */
    public $mCategory = null;

    public function __construct()
    {
        parent::__construct();
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        $this->loadModel('consumerUserModel', 'mConsumer', 'consumer');
        $this->loadModel('ConsumerProductModel', 'mProduct', 'consumer');
        $this->loadModel('ConsumerCategoryModel', 'mCategory', 'consumer');
        $this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');

    }

    /**
     * 首页
     */
    public function index()
    {
        $s = date('Y-m-d', time());
        $startTime = strtotime($s);
        $endTime = strtotime('+1 day', $startTime);
        $endTime = dateFormat($endTime);
        $data = array(
            'timegap' => $s . ' - ' . $endTime,
            'merchant' => $this->mMerchant->getMerchantAll(),
        );
        $this->view('statistics/merchant/index', $data, 'datatable,date_range_picker,select2');
    }

    public function getList()
    {
        $timeGap = trim(get('timegap'));
        if ($timeGap) {
            $timeGapArr = explode(' - ', $timeGap);
            $startTime = strtotime($timeGapArr[0]);
            $endTime = strtotime($timeGapArr[1]) + 86399;
        } else {
            $startTime = strtotime(date('Y-m-d', time()));
            $endTime = strtotime('+1 day', $startTime);
        }
        $data = $this->lists($startTime, $endTime);
        $merchant = $this->getMerchantProduct();
        foreach ($data['data'] as $k => $v) {
            $data['aaData'][$k][] = $v['shop_name'];
            $data['aaData'][$k][] = $v['product'];
            $data['aaData'][$k][] = isset($merchant[$v['merchant_id']]) ? $merchant[$v['merchant_id']] : '0';
            $total = adminCreateBtn(array(
                'label' => $v['total'],
                'attr' => array(
                    'href' => getUrl('statistics/merchant/product?id=' . $v['merchant_id'] . '&stime=' . $startTime . '&etime=' . $endTime),
                    'class' => 'deco blue',
                    'target' => "_blank"
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'statistics',
                    'key' => 'merchant-product'
                )
            ));
            $data['aaData'][$k][] = empty($total) ? $v['total'] : $total;
            $data['aaData'][$k][] = adminCreateBtn(array(
                'label' => '详情',
                'attr' => array(
                    'href' => getUrl('statistics/merchant/product?id=' . $v['merchant_id'] . '&stime=' . $startTime . '&etime=' . $endTime),
                    'class' => 'btn green-stripe btn-xs default',
                    'target' => "_blank"
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'statistics',
                    'key' => 'admin-view'
                )
            ));
        }
        unset($data['data']);
        echo json_encode($data);

    }

    /**
     * 商品销量统计
     */
    public function product()
    {
        $id = get('id');
        $sTime = get('stime');
        $eTime = get('etime');
        $url = '?id=' . $id . '&stime=' . $sTime . '&etime=' . $eTime;
//        $url = '?id='.$id;
        $merchant = $this->mMerchant->getInfo($id);
        $pay_type = $this->mOrder->PAY_TYPE;
        unset($pay_type[0]);
        //统计总量
        $total_sale = 0;
        $total_amount = 0;
        $pageNumber = 500;
        $page = 1;
        while (true) {
            $datalist = $this->productList($sTime, $eTime, $page, $pageNumber);
            if (empty($datalist)) {
                break;
            }
            $page++;
            foreach ($datalist as $v) {
                $total_sale += $v['orders'];
                $total_amount += $v['reality_amount'];
            }
        }
        $data = array(
            'pay_type' => $pay_type,
            'total_sale' => $total_sale,
            'total_amount' => $total_amount,
            'custom' => $this->mCategory->getCustomList($id),
            'expense_type' => $this->mOrder->EXPENSE_TYPE,
            'category' => $this->mCategory->getCustomList($id),
            'url' => $url,
            'timegap' => dateFormat($sTime) . ' - ' . dateFormat($eTime),
            'time' => '商家：<i class="critical">' . $merchant['shop_name'] . '</i>',
            'title' => '商品销量'
        );
        $this->view('statistics/merchant/product', $data, 'datatable,select2,date_range_picker');
    }

    /**
     * 商品销售统计列表
     */
    public function getProductList()
    {
        $id = get('id');
        $timeGap = get('timegap');
        if ($timeGap) {
            $timeGapArr = explode(' - ', $timeGap);
            $sTime = strtotime($timeGapArr[0]);
            $eTime = strtotime($timeGapArr[1]) + 86399;
        } else {
            $sTime = get('stime');
            $eTime = get('etime');
        }
        $data = $this->productList($sTime, $eTime);
        foreach ($data['data'] as $k => $v) {
            $data['aaData'][$k][] = $v['name'];
            $data['aaData'][$k][] = $v['category'];
            $data['aaData'][$k][] = $v['orders'];
            $data['aaData'][$k][] = $v['reality_amount'];
            $data['aaData'][$k][] = adminCreateBtn(array(
                'label' => '详情',
                'attr' => array(
                    'href' => getUrl('statistics/merchant/details?id=' . $v['id'] . '&merchant=' . $id . '&stime=' . $sTime . '&etime=' . $eTime),
                    'class' => 'btn green-stripe btn-xs default',
                    'target' => "_blank"
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'statistics',
                    'key' => 'merchant-product'
                )
            ));
        }
        //统计总量
        $total_sale = 0;
        $total_amount = 0;
        $pageNumber = 500;
        $page = 1;
        while (true) {
            $datalist = $this->productList($sTime, $eTime, $page, $pageNumber);
            if (empty($datalist)) {
                break;
            }
            $page++;
            foreach ($datalist as $v) {
                $total_sale += $v['orders'];
                $total_amount += $v['reality_amount'];
            }
        }

        $data['total_sale']=$total_sale;
        $data['total_amount']=$total_amount;
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 明细
     */
    public function details()
    {
        $id = get('id');
        $merchantId = (int)get('merchant');
        $sTime = get('stime');
        $eTime = get('etime');
        $time = dateFormat($sTime) . ' 至 ' . dateFormat($eTime);
        if (!$id || !$merchantId) {
            show_404();
        }
        $url = '?id=' . $id . '&merchant=' . $merchantId . '&stime=' . $sTime . '&etime=' . $eTime;
        $merchant = $this->mMerchant->getInfo($merchantId);
        $product = $this->mProduct->getInfo($id);
        $data = array(
            'url' => $url,
            'time' => '商家：<i class="critical">' . $merchant['shop_name'] . '</i>；商品：<i class="critical">' . $product['name'] . '</i>；时间区间：<i class="critical">' . $time . '</i>',
            'title' => '详情'
        );
        $this->view('statistics/merchant/details', $data, 'datatable,validation,region,select2');
    }

    public function detailsGetList()
    {
        $data = $this->detailsList();
        foreach ($data['data'] as $k => $v) {
            $data['aaData'][$k][] = $v['productName'];
            $data['aaData'][$k][] = $v['category'];
            $data['aaData'][$k][] = $v['code'];
            $data['aaData'][$k][] = dateFormat($v['addtime'], true);
            $data['aaData'][$k][] = dateFormat($v['merchant_take_time'], true);
            $data['aaData'][$k][] = $v['quantity'];
            $data['aaData'][$k][] = $v['price'];
            $data['aaData'][$k][] = $v['reality_amount'];
            $data['aaData'][$k][] = adminCreateBtn(array(
                'label' => '查看',
                'attr' => array(
                    'href' => getUrl('order/home/details?id='.$v['id']),
                    'class' => 'btn green-stripe btn-xs default',
                    'target' => '_blank'
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'classes',
                    'key' => 'edit'
                )
            ));
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 导出
     * @author defcu
     */
    public function export()
    {
        $timeGap = trim(get('timegap'));
        if ($timeGap) {
            $timeGapArr = explode(' - ', $timeGap);
            $startTime = strtotime($timeGapArr[0]);
            $endTime = strtotime($timeGapArr[1]) + 86399;
        } else {
            $startTime = strtotime(date('Y-m-d', time()));
            $endTime = strtotime('+1 day', $startTime);
        }
        $filename = '商家销量统计' . date('Y-m-d', time()) . '.csv';
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=" . $filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo mb_convert_encoding('商家,销量种类,总商品数,总销量', 'gb2312', 'utf-8') . "\n";
        $pageNumber = 500;
        $page = 1;
        $merchant = $this->getMerchantProduct();
        while (true) {
            $list = $this->lists($startTime, $endTime, $page, $pageNumber);
            if (empty($list)) {
                break;
            }
            $page++;
            foreach ($list as $v) {
                $merchant = isset($merchant[$v['merchant_id']]) ? $merchant[$v['merchant_id']] : '0'; //  单客价
                echo mb_convert_encoding($v['shop_name'] . ',' . $v['product'] . ',' . $merchant . "\t" . ',' . $v['total'] . "\t", 'gb2312', 'utf-8') . "\n";
            }
        }
        $ss = date('Y-m-d', $startTime);
        $ee = date('Y-m-d', $endTime);
        echo mb_convert_encoding('时间区间：' . $ss . ' - ' . $ee, 'gb2312', 'utf-8') . "\n";
    }

    /**
     * 导出详情
     */
    public function detailExport()
    {
        $filename = '商品销量详情' . date('Y-m-d', time()) . '.csv';
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=" . $filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo mb_convert_encoding('产品名称,所属分类,订单号,下单时间,接单时间,销售数量,销售单价,销售总额', 'gb2312', 'utf-8') . "\n";
        $pageNumber = 500;
        $page = 1;

        while (true) {
            $data = $this->detailsList($page, $pageNumber);
            if (empty($data)) {
                break;
            }
            $page++;
            foreach ($data as $v) {
                echo mb_convert_encoding($v['productName'] . "\t" . ',' . $v['category'] . "\t" . ',' . $v['code'] . "\t" . ',' . dateFormat($v['addtime'], true)
                        . "\t" . ',' . dateFormat($v['merchant_take_time'], true) . ',' . $v['quantity'] . ',' . $v['price'] . ',' . $v['reality_amount'], 'gb2312', 'utf-8') . "\n";
            }
        }

        $merchantId = get('merchant');
        $sTime = get('stime');
        $eTime = get('etime');
        $status = trim(get('status'));
        $pay_type = (int)get('pay_type');
        $expense_type = (int)get('expense_type');
        $time = dateFormat($sTime) . ' 至 ' . dateFormat($eTime);
        $merchant = $this->mMerchant->getInfo($merchantId, 0, true);
        $str = '';
        if (!empty($status)) {
            $status = explode(',', $status);
            $str = '；状态：';
            foreach ($status as $s) {
                $str .= $this->mOrder->status($s) . '、';
            }
            $str = trim($str, '、');
        }
        if ($pay_type) {
            $str .= '；支付方式：' . $this->mOrder->PAY_TYPE[$pay_type];
        }
        if ($expense_type) {
            $str .= '；消费模式：' . $this->mOrder->EXPENSE_TYPE[$expense_type];
        }
        echo mb_convert_encoding('商家：' . $merchant['shop_name'] . '；时间区间：' . $time . $str, 'gb2312', 'utf-8') . "\n";
    }

    /**
     * 导出商品销量
     */
    public function productExport()
    {
        $filename = '商品销量' . date('Y-m-d', time()) . '.csv';
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=" . $filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo mb_convert_encoding('产品名称,所属分类,销量,总金额', 'gb2312', 'utf-8') . "\n";
        $pageNumber = 500;
        $page = 1;
        $timeGap = get('timegap');
        if ($timeGap) {
            $timeGapArr = explode(' - ', $timeGap);
            $sTime = strtotime($timeGapArr[0]);
            $eTime = strtotime($timeGapArr[1]) + 86399;
        } else {
            $sTime = get('stime');
            $eTime = get('etime');
        }
        while (true) {
            $data = $this->productList($sTime, $eTime, $page, $pageNumber);
            if (empty($data)) {
                break;
            }
            $page++;
            foreach ($data as $v) {
                $d = sprintf('%.2f', $v['reality_amount'] / $v['orders']); // 价格
                $addtime = date('Y-m-d H:i:s', $v['addtime']);
                echo mb_convert_encoding($v['name'] . ',' . $v['category'] . ',' . $v['orders'] . "\t" . ',' . $v['reality_amount'], 'gb2312', 'utf-8') . "\n";
            }
        }

        $id = get('id');
        $sTime = get('stime');
        $eTime = get('etime');
        $time = dateFormat($sTime) . ' 至 ' . dateFormat($eTime);
        $merchant = $this->mMerchant->getInfo($id, 0, true);
        echo mb_convert_encoding('商家：' . $merchant['shop_name'] . '；时间区间：' . $timeGap, 'gb2312', 'utf-8') . "\n";
    }

    /**
     * 平台资金信息
     * @param int $startTime 开始时间
     * @param int $endTime 结束时间
     * @param bool $isOne
     * @param int $page
     * @param int $pageNumber
     * @return array
     * @author heyu
     */
    public function lists($startTime = 0, $endTime = 0, $page = 0, $pageNumber = 0)
    {
        $merchant = trim(get('merchant'));

        if ($startTime) {
            $this->db->where('o.merchant_take_time >= ' . $startTime);
        }
        if ($endTime) {
            $this->db->where('o.merchant_take_time < ' . $endTime);
        }
        if (!empty($merchant)) {
            $merchant = explode(',', $merchant);
            $this->db->where_in('o.merchant_id', $merchant);
        }
        $this->db->select('o.merchant_id,s.shop_name,p.product_id,count(DISTINCT p.product_id) as product,
            count(p.product_id) as total')
            ->join($this->mMerchant->tbShop . ' s', 's.merchant_id=o.merchant_id')
            ->join($this->mOrder->tbOrderProduct . ' p', 'p.order_id = o.id')
            ->where('o.merchant_take_time > 0')
            ->where_in('o.status', array(4, 5,6))
            ->group_by('o.merchant_id');

        if ($page && $pageNumber) {
            $tA = $this->mOrder->appPage($this->mOrder->tbOrder . ' o', $page, false, $pageNumber);
            $tA = $tA['list'];
        } else {
            $tA = $this->mOrder->pagination($this->mOrder->tbOrder . ' o');
        }
        return $tA;
    }

    /**
     * 获取商家上架的商品数量
     * @return array
     */
    public function getMerchantProduct()
    {
        $merchant = trim(get('merchant'));

        $this->db->select('p.merchant_id,count(p.id) as total')
            ->join($this->mMerchant->tbUser . ' m', 'm.id=p.merchant_id')
            ->where('m.status > 1')
            ->where('p.status', 2)
            ->group_by('p.merchant_id');
        if (!empty($merchant)) {
            $merchant = explode(',', $merchant);
            $this->db->where_in('p.merchant_id', $merchant);
        }
        $tA = $this->mProduct->getAll($this->mProduct->tbProduct . ' p');
        $data = array();
        if (!empty($tA)) {
            foreach ($tA as $v) {
                $data[$v['merchant_id']] = $v['total'];
            }
        }
        return $data;
    }

    /**
     * 商品列表
     * @param int $startTime
     * @param int $endTime
     * @param int $page
     * @param int $pageNumber
     * @return array
     */
    public function productList($startTime = 0, $endTime = 0, $page = 0, $pageNumber = 0)
    {
        $id = get('id');
        $category = get('category');
        $pay_type = get('pay_type');
        $name = get('name');
        $custom_category_id = get('custom_category_id');
        $expense_type = get('expense_type');

        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if ($startTime) {
            $this->db->where('o.merchant_take_time >= ' . $startTime);
        }
        if ($endTime) {
            $this->db->where('o.merchant_take_time < ' . $endTime);
        }
        if ($name) {
            $this->db->like('p.name', $name);
        }
        if ($category) {
            $this->db->where('p.category_id', $category);
        }
        if ($custom_category_id) {
            $this->db->where('p.category_id', $custom_category_id);
        }
        if ($pay_type) {
            $this->db->where('o.pay_type', $pay_type);
        }
        if ($expense_type) {
            $this->db->where('o.expense_type', $expense_type);
        }

        if ($iSortCol_0 == 2) {
            $this->db->order_by('orders', $sSortDir_0); // 销量
        } else {
            $this->db->order_by('p.addtime desc'); // 下单日期
        }
        $this->db->select('p.id,p.name,c.cat_name as category,sum(op.quantity) as orders,sum(op.reality_amount) as reality_amount,p.addtime')
            ->join($this->mProduct->tbProductCustomCategory . ' c', 'p.category_id=c.id')
            ->join($this->mOrder->tbOrderProduct . ' op', 'op.product_id=p.id')
            ->join($this->mOrder->tbOrder . ' o', 'op.order_id=o.id')
            ->where('o.merchant_take_time > 0')
            ->where_in('o.status', array(4,5,6))
            ->where(array('o.merchant_id' => $id))
            ->group_by('p.id');
        if ($page > 0 && $pageNumber > 0) {
            $tA = $this->mOrder->appPage($this->mProduct->tbProduct . ' p', $page, false, $pageNumber);
            return $tA['list'];
        } else {
            return $this->mOrder->pagination($this->mProduct->tbProduct . ' p');
        }
    }

    /**
     * 根据时间获取订单明细列表
     * @param int $page
     * @param int $pageNumber
     * @return array
     */
    public function detailsList($page = 0, $pageNumber = 0)
    {
        $id = get('id');
        $merchantId = (int)get('merchant');
        $sTime = get('stime');
        $eTime = get('etime');

        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if ($sTime) {
            $this->db->where('o.merchant_take_time >= ' . $sTime);
        }
        if ($eTime) {
            $this->db->where('o.merchant_take_time < ' . $eTime);
        }

        if ($iSortCol_0 == 4) {
            $this->db->order_by('o.product_amount', $sSortDir_0); // 商品总价
        } else if ($iSortCol_0 == 5) {
            $this->db->order_by('o.shipping_fee', $sSortDir_0); // 物流价格
        } else if ($iSortCol_0 == 6) {
            $this->db->order_by('o.total_amount', $sSortDir_0); // 订单总价
        } else if ($iSortCol_0 == 8) {
            $this->db->order_by('o.merchant_take_time', $sSortDir_0); // 下单日期
        } else {
            $this->db->order_by('o.merchant_take_time desc'); // 下单日期
        }
        $this->db->select('o.id,o.code,o.product_amount,o.total_amount,o.reality_amount,o.shipping_fee,o.addtime,o.merchant_take_time,
                    op.quantity,op.price,op.reality_amount,p.name as productName,pcc.cat_name as category')
            ->join($this->mOrder->tbOrder . ' o', 'op.order_id=o.id')
            ->join($this->mConsumer->tbUser . ' u', 'o.consumer_id=u.id')
            ->join($this->mOrder->tbProduct . ' p', 'op.product_id=p.id')
            ->join($this->mOrder->tbProductCustomCategory . ' pcc', 'pcc.id=p.category_id')
            ->where(array('o.merchant_id' => $merchantId, 'op.product_id' => $id))
            ->where('o.merchant_take_time > 0')
            ->where_in('o.status', array(4, 5, 6));
        if ($page > 0 && $pageNumber > 0) {
            $tA = $this->mOrder->appPage($this->mOrder->tbOrderProduct . ' op', $page, false, $pageNumber);
            return $tA['list'];
        } else {
            return $this->mOrder->pagination($this->mOrder->tbOrderProduct . ' op');
        }
    }
}
